package com.rocketmq.listener;

import com.rocketmq.dao.IOrderMapper;
import com.rocketmq.dao.IProductMapper;
import com.rocketmq.entity.Order;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.messaging.Message;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Component;

@Slf4j
@Component
@RocketMQMessageListener(topic = "consumer_listener", consumerGroup = "consumer_grp_01")
public class ConsumerListener implements RocketMQListener<Order> {

    @Autowired
    private IOrderMapper orderMapper;

    @Autowired
    private IProductMapper productMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private RocketMQTemplate rocketMQTemplate;

    @Override
    public void onMessage(Order order) {
        // 处理broker推送过来的消息
        //创建订单
        order.setStatus(0);
        orderMapper.insertOrder(order);

        System.out.println("生成订单信息");

        //减少库存
        productMapper.delStore(order.getProductId());


        //更新缓存中的数据
//        redisTemplate.opsForValue().increment("product_" + produce.getId(), -1);

        Message<Order> message = MessageBuilder.withPayload(order).build();

        //发送延时信息
        rocketMQTemplate.syncSend("overtime", message, 3000, 4);

        log.info(order.toString());
    }
}
